package com.fanbai.score.common.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.fanbai.score.R;
import com.fanbai.score.common.Manager.ActivityManager;
import com.fanbai.score.common.base.BaseActivity;
import com.fanbai.score.common.base.MyApplication;


@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
public class WebView_Activity extends BaseActivity {

	private String bar_name;
	private ProgressBar pb; // webview加载进度条
	private WebView webview;
	private xWebChromeClient xwebchromeclient;
	private String url;

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected int getLayoutID() {
		return R.layout.activity_webview;
	}

	@Override
	public String getTitleName() {
		bar_name = getIntent().getExtras().getString("barname");
		return bar_name;
	}

	@Override
	public int getTitleBarColor() {
		return R.color.colorPrimary;
	}

	@Override
	public int getTitleLeftName() {
		return R.mipmap.back_click;
	}

	@Override
	public void onClickTitleLeft() {
		ActivityManager.getInstance().finishActivity();
	}

	@Override
	protected void initView() {
		initwidget();
		url = getIntent().getExtras().getString("url");

		webview.getSettings().setDisplayZoomControls(false);
		webview.getSettings().setLoadsImagesAutomatically(true); // 支持自动加载图片
		synCookies(ctx, url);
		webview.loadUrl(url);
	}

	@Override
	protected void initData() {

	}

	@Override
	protected void initListener() {

	}

	private void initwidget() {
		// TODO Auto-generated method stub
		pb = (ProgressBar) findViewById(R.id.pb);
		pb.setMax(100);

		webview = (WebView) findViewById(R.id.video_webview);

		WebSettings ws = webview.getSettings();
		ws.setBuiltInZoomControls(true);// 隐藏缩放按钮
		ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
		ws.setUseWideViewPort(true);// 可任意比例缩放
		ws.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
		ws.setSavePassword(true);
		ws.setSaveFormData(true);// 保存表单数据
		ws.setJavaScriptEnabled(true);
		ws.setGeolocationEnabled(true);// 启用地理定位
		ws.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
		ws.setDomStorageEnabled(true);

		webview.getSettings().setJavaScriptEnabled(true);
		webview.getSettings().setSupportZoom(true);
		webview.getSettings().setBuiltInZoomControls(true);
		webview.getSettings().setDefaultZoom(ZoomDensity.FAR);

		xwebchromeclient = new xWebChromeClient();
		webview.setWebChromeClient(xwebchromeclient);
		webview.setWebViewClient(new xWebViewClientent());
		webview.setDownloadListener(new MyWebViewDownLoadListener());
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (webview.canGoBack()) {
				webview.goBack();
				return true;
			} else {
				webview.loadUrl("about:blank");
				// mTestWebView.loadData("", "text/html; charset=UTF-8", null);
				this.finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 处理Javascript的对话框、网站图标、网站标题以及网页加载进度等
	 * 
	 * @author
	 */
	public class xWebChromeClient extends WebChromeClient {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			pb.setProgress(newProgress);
			if (newProgress == 100) {
				pb.setVisibility(View.GONE);
			}
			super.onProgressChanged(view, newProgress);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	/**
	 * 处理各种通知、请求等事件
	 * 
	 * @author
	 */
	public class xWebViewClientent extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.i("webviewtest", "shouldOverrideUrlLoading: " + url);
			//界面内跳转的监听处理，注意判断顺序

			//跳转本地应用
			if (url.startsWith("intent://")) {
				Intent intent;
				try {
					intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
					intent.addCategory("android.intent.category.BROWSABLE");
					intent.setComponent(null);
//					intent.setSelector(null);
					startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(WebView_Activity.this, "应用未安装或未找到", Toast.LENGTH_LONG).show();
				}
				return true;
			}
			if (!(url.startsWith("http") || url.startsWith("https"))) {
				return true;
			}
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			String t = view.getTitle();
			if (null == t || t.equals("")) {
				return;
			}
			if (t.length() > 10) {
				t = t.substring(0, 10) + "...";
			}
			if (null == bar_name || "".equals(bar_name)) {
				toolbar.setTitle(t);
			}
		}
	}

	private class MyWebViewDownLoadListener implements DownloadListener {
		@Override
		public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
									long contentLength) {
			if (url.contains(".apk")){
				Uri uri = Uri.parse(url);
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			}
		}
	}

/** 
  * 同步一下cookie 
  */
	public static void synCookies(Context context, String url){
		CookieSyncManager.createInstance(context);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);
		cookieManager.removeSessionCookie();//移除  
		cookieManager.setCookie(url, MyApplication.getInstanti().getCookieStore().getCookies().toString());//cookies是在HttpClient中获得的cookie  
		CookieSyncManager.getInstance().sync();
	}
}
